package Server; //done

import Common.Settings;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 * This is the main class of the Server.
 * @author waleed
 * @author kamil
 */
public class CCRM_Server_Main{
	
    /**
     * Server main function.
     * @param args
     */
	public static void main(String[] args) {
	    final ServerLoginWindow serverLoginWindow = new ServerLoginWindow();
	    serverLoginWindow.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
	    serverLoginWindow.setBounds(Settings.Screen_x,Settings.Screen_y, 600, 480 ); // set frame size  
	    serverLoginWindow.getStartButton().addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {	
				 int port = 0; //Port to listen on
				 try{
				     	port = serverLoginWindow.getPort(); //Get port from command line
				     	if (port == -1 || port < 0){
				     		JOptionPane.showMessageDialog(null, "Ilegal port number");
				     		port = Settings.Default_Port; //Set port to 5555
				     	}
				     	if (port == 0)
				     		port = Settings.Default_Port; //Set port to 5555			     		
				    }
				    catch(Throwable t){
				    	port = Settings.Default_Port; //Set port to 5555
				    }
				    char[] char_password = serverLoginWindow.getMySQLpassword();
				    int len = char_password.length;
				    String password = "";
				    for (int i=0; i < len; i++)
				    	password = password+char_password[i];
				    ConnectionTOmysql.setPassword(password);
				    ConnectionTOmysql.setUsername(serverLoginWindow.getMySQLuserName());
				    ConnectionTOmysql.setDB_Name(serverLoginWindow.getMySQL_DB_Name());
				    CCRM_Server_Controller ccrm_Server_Controller = new CCRM_Server_Controller(port);
				    try {	
				    	ConnectionTOmysql connectiontomysql = new ConnectionTOmysql();
				    	ccrm_Server_Controller.listen(); //Start listening for connections
				    	ServerStartWindow serverStartWindow = new ServerStartWindow(port);
				    	serverLoginWindow.setBounds(Settings.Screen_x,Settings.Screen_y, 400, 300 ); // set frame size
				    	serverStartWindow.setVisible(true);
				    	serverLoginWindow.setVisible(false);			    							
				    }
				    catch (Exception ex) {
				    	JOptionPane.showMessageDialog(null, "ERROR - Could not listen for clients!");						
				    }				    
			}
		});	    
	    serverLoginWindow.setVisible( true ); // display frame	   
	  }
	}
	